const WorktileWeb = require("lib-worktile/lib").web.WorktileWeb;
const util = require("util");

const LIST_ID = "5db41d266fbcac100665e36a";


/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{value:Array<{_id:String,title:String}>}}>}
 * @param {WorktileWeb} wt 
 * @param {String} view_id 
 * @param {Number} page 
 */
function getTasksByViewID(wt, view_id, page = 0) {
  page = parseInt(page);
  if (page < 0) {
    page = 0;
  }
  return new Promise(async resolve => {
    let o_get = await wt.getTasksInListView(LIST_ID, view_id, page);
    if (!o_get.ok) {
      return resolve({
        ok: false,
        msg: `wt.getTasksInListView is not OK:${o_get.msg}`
      });
    }
    if (!(o_get.data && util.isNumber(o_get.data.page_count))) {
      return resolve({
        ok: false,
        msg: `can NOT get page count,the data is ${util.inspect(o_get.data)}`
      });
    }
    let total_pages = o_get.data.page_count;
    if (total_pages == 0) {
      return resolve({
        ok: true,
        msg: `完全没有pending任务`,
        data: {
          value: []
        }
      })
    }
    if (page < total_pages) {
      return resolve({
        ok: true,
        msg: "ok",
        data: {
          value: o_get.data.value
        }
      })
    } else {
      let o_lastPage = await getTasksByViewID(wt, view_id, total_pages - 1);
      return resolve({
        ok: o_lastPage.ok,
        msg: o_lastPage.msg,
        data: o_lastPage.data
      })
    }

  });
}

module.exports = {
  getTasksByViewID: getTasksByViewID
}